/**
 * Created by xinxinran on 2017/1/3.
 */
'use strict';

const commonUtil = require('./commonUtil'),
    propertyUtil = require('./propertyUtil');

function getErrMsg(err){
    if(!err){
        return err;
    }
    if(err instanceof Error){
        return err.message.msg || err.message;
    }else if(err.msg){
        return err.msg;
    }else{
        return err.toString();
    }
}


function getErrCode(err){
    if(!err){
        return -1;
    }
    if(err instanceof Error){
        return err.message.code || -1;
    }else if(err.code){
        return err.code;
    }else{
        return -1;
    }
}

function processToString(obj){
    if(commonUtil.isArrayLike(obj)){
        return commonUtil.each(obj, function(){
            return processToString(this);
        }, null, true);
    }

    obj = commonUtil.toObject(obj);

    return commonUtil.each(obj, function(_, value){
        obj[_] = procValue(value);
    });
}

function procValue(value){
    if(typeof value === 'undefined' || value === null){
        return '';
    }else if(typeof value === 'number'){
        return value + '';
    }else if(value instanceof Date){
        return commonUtil.getFormattedDate(value);
    }else if(value instanceof Object){
        return processToString(value);
    }else{
        return value.toString();
    }
}


exports.makeSuccessResponse = function(result, template){
    const resp = template.getObject();
    template.setCode(resp, 'SUCCESS');
    template.setMessage(resp, '操作成功');
    result && template.setResult(resp, propertyUtil.getProperty('force2String') ?processToString(result) : result);
    return resp;
};

exports.makeErrorResponse = function(err, template, errCode){
    const resp = template.getObject();
    template.setCode(resp, getErrCode(err));
    template.setMessage(resp, getErrMsg(err));
    //template.setResult(resp, null);
    return resp;
};
